package com.hsource.doctorcenter.service.problem.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hsource.common.utils.CommonResp;
import com.hsource.common.utils.DateUtil;
import com.hsource.doctorcenter.domain.clinic.Clinic;
import com.hsource.doctorcenter.domain.dict.DictData;
import com.hsource.doctorcenter.domain.doctor.Doctor;
import com.hsource.doctorcenter.domain.order.Order;
import com.hsource.doctorcenter.domain.order.OrderDoctor;
import com.hsource.doctorcenter.domain.problem.ProblemHistory;
import com.hsource.doctorcenter.domain.user.UserBase;
import com.hsource.doctorcenter.feign.UserFeignClient;
import com.hsource.doctorcenter.mapper.ClinicMapper;
import com.hsource.doctorcenter.mapper.DoctorMapper;
import com.hsource.doctorcenter.mapper.OrderDoctorMapper;
import com.hsource.doctorcenter.service.api.IApiService;
import com.hsource.doctorcenter.service.dict.IDictDataService;
import com.hsource.doctorcenter.service.doctor.IDoctorService;
import com.hsource.doctorcenter.service.order.IOrderService;
import com.hsource.doctorcenter.service.problem.ProblemService;
import com.hsource.doctorcenter.util.OSSUtil;
import com.hsource.doctorcenter.util.RedisUtil;
import com.hsource.doctorcenter.util.StringUtils;
import com.hsource.doctorcenter.webSocket.WebSocketUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.*;

/**
 * @author yangYang
 * @version 1.0
 * @date 2020/9/28 11:48
 * @describe 问题（图文急诊 快速提问 快捷电话）业务逻辑层
 */
@Service
@Slf4j
public class ProblemServiceImpl implements ProblemService {
    @Autowired
    private IApiService apiService;
    @Autowired
    private IDictDataService dictDataService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private ClinicMapper clinicMapper;
    @Autowired
    private OrderDoctorMapper orderDoctorMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private OSSUtil ossUtil;
    @Autowired
    private IDoctorService doctorService;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 缓存处理redis问题详情
     * @param userId
     * @param problemId
     * @return
     */
    @Override
    public List<LinkedHashMap<String,String>> getProblemDetailRedis(String userId,String problemId) throws ParseException, NoSuchAlgorithmException {
        List<LinkedHashMap<String,String>> mapList=new ArrayList<>();
        String problemDetailKey = redisUtil.keyBuilder("problem","detail", userId, problemId);
        if(redisUtil.hasKey(problemDetailKey)){
            List<Object> objects = redisUtil.lGet(problemDetailKey, 0, -1);
            objects.stream().forEach(o->{
                LinkedHashMap<String,String> linkedHashMap = JSONObject.parseObject(JSONObject.toJSONString(o), LinkedHashMap.class);
                mapList.add(linkedHashMap);
            });
            mapList.sort((a,b)->a.get("created_time_ms").compareTo(b.get("created_time_ms")));
        }else{
            return getProblemDetail(userId,problemId);
        }
        return mapList;
    }

    /**
     * 获取问题详情
     * @param userId 用户id
     * @param problemId 问题id
     * @return
     * @throws ParseException
     * @throws NoSuchAlgorithmException
     */
    @Override
    public List<LinkedHashMap<String,String>> getProblemDetail(String userId,String problemId) throws ParseException, NoSuchAlgorithmException {
        String problemDetailKey = redisUtil.keyBuilder("problem","detail", userId, problemId);
        if(redisUtil.hasKey(problemDetailKey)){
            redisUtil.del(problemDetailKey);
        }
        String problemDetail = apiService.getProblemDetail(problemId, userId);
        JSONObject jsonObject = JSONObject.parseObject(problemDetail);
        List<LinkedHashMap<String,String>> mapList=new ArrayList<>();
        String ubImage="";
        try{
            Object userInfo = userFeignClient.getUserInfo(userId);
            CommonResp commonResps = JSONObject.parseObject(JSONObject.toJSONString(userInfo), CommonResp.class);
            JSONObject jo= (JSONObject)commonResps.getData();
            UserBase ub = JSONObject.parseObject(jo.getString("userInfo"), UserBase.class);
            ubImage=ub.getImage();
        }catch (Exception e){
            e.printStackTrace();
        }
        if(jsonObject.getString("error").equals("0")){
            if(jsonObject.containsKey("doctor")) {
                JSONObject doctorjSON = JSONObject.parseObject(jsonObject.get("doctor").toString());
                String doctorId = doctorjSON.getString("id");
                Doctor doctor = doctorService.selectDoctorByDoctorId(doctorId);
                if (jsonObject.containsKey("content")) {
                    JSONArray content = JSONObject.parseArray(jsonObject.get("content").toString());
                    String finalUbImage = ubImage;
                    content.stream().forEach(c->{
                        Map<String,String> map = JSONObject.parseObject(c.toString(), Map.class);
                        String messageType = map.get("type");
                        String created_time_ms = String.valueOf(map.get("created_time_ms"));
                        JSONObject.parseArray(map.get("content")).stream().forEach(cc->{
                            Map<String,String> map1 = JSONObject.parseObject(cc.toString(), Map.class);
                            LinkedHashMap<String,String> lmap=new LinkedHashMap<>();
                            String contentType = map1.get("type");
                            lmap.put("type",contentType);
                            lmap.put("duration","0");
                            lmap.put("imageWidth", "0");
                            lmap.put("imageHeight", "0");
                            if(contentType.equals("text")){
                                lmap.put("content",map1.get("text"));
                            }else{
                                lmap.put("content",map1.get("file"));
                                if(contentType.equals("audio")){
                                    try {
                                        lmap.put("duration",String.valueOf(WebSocketUtil.getDuration(map1.get("file"))+1));
                                    } catch (MalformedURLException e) {

                                    }
                                }
                                if(contentType.equals("image")){
                                    try {
                                        BufferedImage file = WebSocketUtil.getBufferedImage(map1.get("file"));
                                        lmap.put("imageWidth", String.valueOf(file.getWidth()));
                                        lmap.put("imageHeight", String.valueOf(file.getHeight()));
                                    }catch (Exception e){

                                    }
                                }
                            }
                            lmap.put("doctorId",doctorId);
                            lmap.put("problemId",problemId);
                            lmap.put("userId",userId);
                            lmap.put("contentType",messageType);
                            lmap.put("doctorImage",doctor.getImage());
                            lmap.put("userImage", finalUbImage);
                            lmap.put("created_time_ms", created_time_ms);
                            mapList.add(lmap);
                            redisUtil.lSet(problemDetailKey,lmap);
                        });
                    });
                }
            }
        }
        mapList.sort((a,b)->a.get("created_time_ms").compareTo(b.get("created_time_ms")));
        if(redisUtil.hasKey(problemDetailKey)) {
            redisUtil.expire(problemDetailKey, 2592000);
        }
        return mapList;
    }
    /**
     * 追问
     * @param request
     * @param type
     * @param problemId
     * @param userId
     * @param doctorId
     */
    public void questionProblem(MultipartHttpServletRequest request, String type, Integer problemId,String userId,String doctorId){

    }

    /**
     * 获取问题历史
     * @param userId 用户id
     * @param startNum 开始条数
     * @param count 总数
     * @param type 类型
     * @return
     * @throws ParseException
     * @throws NoSuchAlgorithmException
     */
    @Override
    public Map<String,Object> getHistoricalQuestions(String userId,Integer startNum,Integer count,String type) throws ParseException, NoSuchAlgorithmException {
        Map<String,Object> map=new HashMap<>();
        List<ProblemHistory> problemHistoryList=new ArrayList<>();
        if(type.equals("imagetext")) {
            String resultString = apiService.historicalQuestions(userId, startNum, count);
            log.info(resultString);
            if(resultString.equals("[]")){
                return map;
            }
            JSONArray jsonArray = JSONArray.parseArray(resultString);
            jsonArray.stream().forEach(jo->{
                JSONObject jsonObject = JSONObject.parseObject(jo.toString());
                JSONObject problemjsonObject=JSONObject.parseObject(jsonObject.getString("problem"));
                ProblemHistory problemHistory = JSONObject.parseObject(problemjsonObject.toString(), ProblemHistory.class);
                problemHistory.setCreateTime(DateUtil.getDateFromStr(problemjsonObject.getString("created_time"),""));
                problemHistory.setViewed(problemjsonObject.getBoolean("is_viewed"));
                problemHistory.setStatus(problemjsonObject.getString("status"));
                problemHistory.setJumpDetails(false);
                problemHistory.setOrderType("图文咨询");
                List<DictData> dictDatas = dictDataService.selectDictDataByType("sys_problem_status");
                dictDatas = JSONObject.parseArray(JSONObject.toJSONString(dictDatas), DictData.class);
                String dictLabel = dictDatas.stream().filter(d -> d.getDictValue().equals(problemHistory.getStatus())).findFirst().get().getDictLabel();
                problemHistory.setStatusName(dictLabel);
                if(StringUtils.isNotNull(jsonObject.get("doctor"))) {
                    problemHistory.setJumpDetails(true);
                    JSONObject doctorJsonObject = JSONObject.parseObject(jsonObject.getString("doctor"));
                    problemHistory.setDoctorId(doctorJsonObject.getString("id"));
                    problemHistory.setDoctorName(doctorJsonObject.getString("name"));
                    problemHistory.setDoctorImage(doctorJsonObject.getString("image"));
                }else{
                    problemHistory.setDoctorName("图文咨询");
                }
                problemHistoryList.add(problemHistory);
            });
        }
        if(type.equals("phone")){
            Order order=new Order();
            order.setOrderType("QuickCall");
            order.setUserId(userId);
            List<Order> orders=new ArrayList<>();
            List<Order> order1 = orderService.selectOrderList(order);
            if(StringUtils.isNotNull(order1)&&order1.stream().count()>0){
                orders.addAll(order1);
            }
            order.setOrderType("DirectedPhone");
            List<Order> order2 = orderService.selectOrderList(order);
            if(StringUtils.isNotNull(order2)&&order2.stream().count()>0){
                order2.stream().forEach(ot->{
                    if(StringUtils.isBlank(ot.getClinicNo())){
                        OrderDoctor od=new OrderDoctor();
                        od.setOrderId(ot.getId());
                        List<OrderDoctor> orderDoctors = orderDoctorMapper.selectOrderDoctorList(od);
                        Doctor doctor = doctorMapper.selectDoctorByDoctorId(orderDoctors.stream().findFirst().get().getDoctorId());
                        ot.setClinicNo(doctor.getClinic_no());
                    }
                });
                orders.addAll(order2);
            }
            orders.stream().forEach(o->{
                ProblemHistory problemHistory=new ProblemHistory();
                problemHistory.setJumpDetails(false);
                problemHistory.setViewed(false);
                problemHistory.setCreateTime(o.getCreateTime());
                JSONArray jsonArray = JSONObject.parseArray(o.getContent());
                jsonArray.stream().forEach(ja->{
                    JSONObject jsonObject = JSONObject.parseObject(ja.toString());
                    if(jsonObject.getString("type").equals("text")){
                        problemHistory.setTitle(jsonObject.getString("text"));
                        problemHistory.setAsk(jsonObject.getString("text"));
                    }
                });
                List<DictData> dictDatas = dictDataService.selectDictDataByType("sys_order_status");
                dictDatas = JSONObject.parseArray(JSONObject.toJSONString(dictDatas), DictData.class);
                String dictLabel = dictDatas.stream().filter(d -> d.getDictValue().equals(o.getPayStatus())).findFirst().get().getDictLabel();
                problemHistory.setStatusName(dictLabel);
                problemHistory.setStatus(o.getPayStatus());
                Clinic clinic = clinicMapper.selectClinicById(o.getClinicNo());
                problemHistory.setClinicName(clinic.getClinicName());
                if(o.getOrderType().equals("QuickCall")) {
                    problemHistory.setOrderType("快捷咨询");
                    problemHistory.setId(o.getProblemId());
                    OrderDoctor orderDoctor = orderDoctorMapper.selectOrderDoctorByProblemId(o.getProblemId());
                    if (StringUtils.isNotNull(orderDoctor)) {
                        Doctor doctor = doctorMapper.selectDoctorByDoctorId(orderDoctor.getDoctorId());
                        problemHistory.setDoctorName(doctor.getName());
                        problemHistory.setDoctorImage(doctor.getImage());
                        problemHistory.setDoctorId(doctor.getDoctor_id());
                    } else {
                        problemHistory.setDoctorName("电话咨询");
                    }
                }
                if(o.getOrderType().equals("DirectedPhone")){
                    problemHistory.setOrderType("定向咨询");
                    OrderDoctor od=new OrderDoctor();
                    od.setOrderId(o.getId());
                    List<OrderDoctor> orderDoctors = orderDoctorMapper.selectOrderDoctorList(od);
                    if(orderDoctors.stream().count()>0){
                        OrderDoctor orderDoctor = orderDoctors.stream().findFirst().get();
                        problemHistory.setId(orderDoctor.getProblemId());
                        Doctor doctor = doctorMapper.selectDoctorByDoctorId(orderDoctor.getDoctorId());
                        problemHistory.setDoctorName(doctor.getName());
                        problemHistory.setDoctorImage(doctor.getImage());
                        problemHistory.setDoctorId(doctor.getDoctor_id());
                    } else {
                        problemHistory.setDoctorName("电话咨询");
                    }
                }
                problemHistoryList.add(problemHistory);
            });
            order.setOrderType("DirectedPhone");
        }
        problemHistoryList.sort((a,b)->b.getCreateTime().compareTo(a.getCreateTime()));
        map.put("problemHistoryList",problemHistoryList);
        return map;
    }
}
